登录 白背景

https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/

/**
 * Definition for a singly-linked list.
 * class ListNode {
 *     public $val = 0;
 *     public $next = null;
 *     function __construct($val) { $this->val = $val; }
 * }
 */
class Solution {

    /**
     * @param ListNode $head
     * @param Integer $n
     * @return ListNode
     */
    function removeNthFromEnd($head, $n) {
        //当前位置为倒数第一个
        $i = 1;
        //节点总数
        $count = 0;
        //遍历节点
        $now = $head;
        //倒数目标节点
        $targetNode = $head;
        while(!empty($now)){
            $count++;
            //取倒数目标节点前一个节点
            if($i <= $n + 1){
                $targetNode = $head;
                //这里多加了一次
                $i++;
            }else{
                //跟随now节点往后递推
                $targetNode = $targetNode->next;
            }
            $now = $now->next;
        }
        if($head == $targetNode && $i != $n + 2){
            //删除的是头节点
            return $targetNode->next;
        }else{
            $targetNode->next = $targetNode->next->next;
        }
        // echo $count,',',$i,',',$n,"\n";
        return $head;
    }
}

跟php一样思路的解法

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        i = 1
        count = 0
        now = head
        targetNode = head
        while now:
            count += 1
            if i <= n + 1:
                i += 1
            else:
                targetNode = targetNode.next
            now = now.next
        if head == targetNode and i != n + 2:
            return targetNode.next
        else:
            targetNode.next = targetNode.next.next
        return head

python更简洁的解法

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        #快指针和慢指针控制在两个距离,当first到头,second就走到了指定位置
        first = head
        second = head
        while first:
            #当n用完,表示快慢指针已到达指定位置
            if n + 1 > 0:
                n -= 1
            else:
                # if not first.next:
                second = second.next
            first = first.next
        # print(second,n)
        if head == second and n == 0:
            return second.next
        else:
            second.next = second.next.next
        return head